from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import VepParameter
from app.utils.decorators import admin_required

vep_parameters_bp = Blueprint('vep_parameters', __name__)

@vep_parameters_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_vep_parameters():
    """获取VEP参数列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取搜索参数
    vep_year = request.args.get('vepYear', '')
    vep_city = request.args.get('vepCity', '')
    vep_district = request.args.get('vepDistrict', '')
    vep_town = request.args.get('vepTown', '')
    
    query = VepParameter.query
    
    # 根据搜索条件过滤
    if vep_year:
        query = query.filter(VepParameter.year == vep_year)
    if vep_city:
        query = query.filter(VepParameter.vepCity.contains(vep_city))
    if vep_district:
        query = query.filter(VepParameter.vepDistrict.contains(vep_district))
    if vep_town:
        query = query.filter(VepParameter.vepTown.contains(vep_town))
    
    # 限制最多返回100条数据
    total_count = query.count()
    if total_count > 100:
        # 如果总数超过100，调整分页参数
        per_page = min(per_page, 100)
        page = min(page, (total_count + per_page - 1) // per_page)
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    parameters = pagination.items
    
    return jsonify({
        'vep_parameters': [param.to_dict() for param in parameters],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': min(pagination.total, 100),
            'pages': pagination.pages
        }
    }), 200

@vep_parameters_bp.route('/<int:param_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_vep_parameter(param_id):
    """获取单个VEP参数详情"""
    parameter = VepParameter.query.get(param_id)
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    return jsonify({
        'vep_parameter': parameter.to_dict()
    }), 200

@vep_parameters_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_vep_parameter():
    """创建VEP参数"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['year', 'vepName', 'vepCity', 'vepDistrict', 'vepTown']
    for field in required_fields:
        if not data.get(field):
            return jsonify({'message': f'字段 {field} 不能为空'}), 400
    
    # 检查唯一性约束
    existing = VepParameter.query.filter_by(
        year=data['year'],
        vepName=data['vepName'],
        vepCity=data['vepCity'],
        vepDistrict=data['vepDistrict'],
        vepTown=data['vepTown']
    ).first()
    
    if existing:
        return jsonify({'message': '该地区该年份的VEP项目参数已存在'}), 400
    
    # 创建新参数
    parameter = VepParameter(
        year=data['year'],
        vepName=data['vepName'],
        vepCity=data['vepCity'],
        vepDistrict=data['vepDistrict'],
        vepTown=data['vepTown'],
        projectArea=data.get('projectArea'),
        directSalesRevenue=data.get('directSalesRevenue'),
        processedProductsRevenue=data.get('processedProductsRevenue'),
        townArea=data.get('townArea'),
        regulationServiceValue=data.get('regulationServiceValue'),
        tourismHealthRevenue=data.get('tourismHealthRevenue'),
        roomPrice=data.get('roomPrice'),
        averageOccupancyRate=data.get('averageOccupancyRate'),
        roomCount=data.get('roomCount'),
        realEstateRevenue=data.get('realEstateRevenue'),
        dailyVisitorFlow=data.get('dailyVisitorFlow'),
        perCapitaDailyConsumption=data.get('perCapitaDailyConsumption'),
        ticketPrice=data.get('ticketPrice'),
        creator=str(current_user_id)
    )
    
    try:
        db.session.add(parameter)
        db.session.commit()
        return jsonify({
            'message': '创建成功',
            'vep_parameter': parameter.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@vep_parameters_bp.route('/<int:param_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_vep_parameter(param_id):
    """更新VEP参数"""
    current_user_id = get_jwt_identity()
    parameter = VepParameter.query.get(param_id)
    
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    data = request.get_json()
    
    # 允许更新的字段
    allowed_fields = [
        'projectArea', 'directSalesRevenue', 'processedProductsRevenue',
        'townArea', 'regulationServiceValue', 'tourismHealthRevenue',
        'roomPrice', 'averageOccupancyRate', 'roomCount', 'realEstateRevenue',
        'dailyVisitorFlow', 'perCapitaDailyConsumption', 'ticketPrice'
    ]
    
    # 更新字段
    for field in allowed_fields:
        if field in data:
            setattr(parameter, field, data[field])
    
    parameter.updater = str(current_user_id)
    
    try:
        db.session.commit()
        return jsonify({
            'message': '更新成功',
            'vep_parameter': parameter.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

@vep_parameters_bp.route('/<int:param_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_vep_parameter(param_id):
    """删除VEP参数"""
    parameter = VepParameter.query.get(param_id)
    
    if not parameter:
        return jsonify({'message': '参数不存在'}), 404
    
    try:
        db.session.delete(parameter)
        db.session.commit()
        return jsonify({'message': '删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除失败: {str(e)}'}), 500 